package com.ktg.mes.unit.tableVersion.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.ktg.common.utils.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.mes.unit.tableVersion.domain.ZjmTableModel;
import com.ktg.mes.unit.tableVersion.mapper.ZjmTableModelMapper;
import com.ktg.mes.unit.tableVersion.service.IZjmTableModelService;
import com.ktg.mes.wm.domain.WmMaterialStock;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;



/**
 * 版本记录Service业务层处理
 *
 * @author byteco
 * @date 2022-12-13
 */
@Service
public class ZjmTableModelServiceImpl extends ServiceImpl<ZjmTableModelMapper, ZjmTableModel> implements IZjmTableModelService
{


    /**
     * 查询版本记录
     *
     * @param entity 版本记录
     * @param page 分页对象
     * @return 版本记录
     */
    @Override
    public IPage<ZjmTableModel> queryPageList(ZjmTableModel entity, Page<ZjmTableModel> page) {
        QueryWrapper<ZjmTableModel> lqw = new QueryWrapper<ZjmTableModel>(entity);
        lqw.orderByDesc("create_time");
        IPage<ZjmTableModel> pageList = this.page(page, lqw);
        return pageList;
    }

    /**
     * 查询版本记录
     *
     * @param entity 版本记录
     * @return 版本记录
     */
    @Override
    public List<ZjmTableModel> queryList(ZjmTableModel entity) {
        QueryWrapper<ZjmTableModel> lqw = new QueryWrapper<ZjmTableModel>(entity);
        lqw.orderByDesc("create_time");
        return this.list(lqw);
    }

    public ZjmTableModel getInfo(Long id)
    {
        return this.getById(id);
    }


    /**
     * 新增版本记录
     *
     * @param entity 版本记录
     * @return 结果
     */
    @Override
    public void insert(ZjmTableModel entity)
    {
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        this.save(entity);
    }

    /**
     * 修改版本记录
     *
     * @param entity 版本记录
     * @return 结果
     */
    @Override
    public boolean update(ZjmTableModel entity)
    {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return this.updateById(entity);
    }

    /**
     * 批量删除版本记录
     *
     * @param recordIds 需要删除的版本记录主键
     * @return 结果
     */
    @Override
    public boolean delete(Long[] recordIds)
    {

        return this.removeByIds(Arrays.asList(recordIds));
    }

    /**
     * 删除版本记录信息
     *
     * @param recordId 版本记录主键
     * @return 结果
     */
    @Override
    public boolean delete(Long recordId)
    {
        return this.removeById(recordId);
    }

    private LambdaQueryWrapper<ZjmTableModel> buildQueryWrapper(ZjmTableModel entity) {
        LambdaQueryWrapper<ZjmTableModel> lqw = Wrappers.lambdaQuery();
                    lqw.like(StringUtils.isNotBlank(entity.getTableName()), ZjmTableModel::getTableName, entity.getTableName());
                    lqw.eq(StringUtils.isNotBlank(entity.getTableVersion()), ZjmTableModel::getTableVersion, entity.getTableVersion());
                    lqw.eq(StringUtils.isNotBlank(entity.getMessage()), ZjmTableModel::getMessage, entity.getMessage());
        return lqw;
    }


    public void createOrUpdateTables(){
        List<ZjmTableModel> list = new ArrayList<>();
        list.add(new ZjmTableModel(WmMaterialStock.class,"202212131209","库存管理"));
        list.add(new ZjmTableModel(WmMaterialStock.class,"202212131209","库存管理"));


    }




    //使用说明，需要创建创建基础表的存储过程
    /*

        -- 创建创建基础表的存储过程
        DROP PROCEDURE if EXISTS createTable;
        CREATE PROCEDURE createTable(in tableName VARCHAR(255),in tableDes varchar(255))
        BEGIN
            set @tName := tableName;
            if POSITION(' ' in @tName) = 0 then
                set @sqlName := CONCAT("CREATE TABLE if NOT EXISTS ",@tName," (
                        `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
                        `remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注',
                        `create_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人',
                        `create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
                        `update_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改人',
                        `update_time` datetime NULL DEFAULT NULL COMMENT '修改时间',
                        PRIMARY KEY (`id`) USING BTREE
                    ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '",tableDes,"' ROW_FORMAT = Dynamic;");
                PREPARE STMT FROM @sqlName;
                EXECUTE STMT;
                SELECT 1;
            end if;
        END;
    */


    // 添加数据库字段
    /*

        DROP PROCEDURE if EXISTS alertColum;
        CREATE PROCEDURE alertColum(in tableName VARCHAR(255),in columnName VARCHAR(255),in typeStr VARCHAR(255),in defaultStr VARCHAR(255),in desStr VARCHAR(255))
        BEGIN
            if EXISTS (select * from information_schema.columns where TABLE_SCHEMA = 'mes_text' and table_name = tableName and column_name = columnName)
            then
            SELECT 2;
            set @sqlStr := CONCAT("ALTER TABLE `",tableName,"` MODIFY COLUMN `",columnName,"` ",typeStr," DEFAULT ",defaultStr," COMMENT '",desStr,"'");
            PREPARE STMT FROM @sqlStr;
            EXECUTE STMT;

            ELSE
            SELECT 1;
            set @sqlStr := CONCAT("ALTER TABLE `",tableName,"` ADD COLUMN `",columnName,"` ",typeStr," DEFAULT ",defaultStr," COMMENT '",desStr,"'");
            PREPARE STMT FROM @sqlStr;
            EXECUTE STMT;


            END if;
        -- 	PREPARE STMT FROM @sqlStr;
        END;

        CALL alertColum('demo','name2','VARCHAR(255)','0','测试名称2');

    * */

    /*

    DROP PROCEDURE if EXISTS alertColum;
CREATE PROCEDURE alertColum(in tableName VARCHAR(255),in oldColumnName VARCHAR(255),in columnName VARCHAR(255),in typeStr VARCHAR(255),in defaultStr VARCHAR(255),in desStr VARCHAR(255))
BEGIN
		if EXISTS (select * from information_schema.columns where TABLE_SCHEMA = 'mes_text' and table_name = tableName and column_name = columnName)
	then

	ELSEIF EXISTS (select * from information_schema.columns where TABLE_SCHEMA = 'mes_text' and table_name = tableName and column_name = columnName)
	then
	SELECT 2;
	set @sqlStr := CONCAT("ALTER TABLE `",tableName,"` MODIFY COLUMN `",columnName,"` ",typeStr," DEFAULT ",defaultStr," COMMENT '",desStr,"'");
	PREPARE STMT FROM @sqlStr;
	EXECUTE STMT;

	ELSE
	SELECT 1;
	set @sqlStr := CONCAT("ALTER TABLE `",tableName,"` ADD COLUMN `",columnName,"` ",typeStr," DEFAULT ",defaultStr," COMMENT '",desStr,"'");
	PREPARE STMT FROM @sqlStr;
	EXECUTE STMT;


	END if;
-- 	PREPARE STMT FROM @sqlStr;
END;

CALL alertColum('demo','0','name2','VARCHAR(255)','0','测试名称2');

    * */

}
